/**
 * 
 */
package com.jinmei.mail;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.jinmei.mail.bean.NewMailInfo;
import com.jinmei.mail.client.ExmailClientProxy;
import com.jinmei.mail.oauth.OAuth;
import com.jinmei.mail.request.ExmailClientRequest;
import com.jinmei.mail.response.ListeningResponse;
import com.jinmei.mail.util.ExmailUtils;
import com.jinmei.remote.client.URLConnectionClient;
import com.jinmei.remote.util.RequestUtils;
import com.jinmei.utils.JinmeiConsts;
import com.jinmei.utils.ResourceManager;

/**
 * @author richard
 *
 */
public class ExmailLongConnection {
	
	private static Logger logger = Logger.getLogger(ExmailLongConnection.class);
	
	private static ExmailClientProxy client =
			new ExmailClientProxy(new URLConnectionClient() {
				@Override
				protected String saveStreamAsString(InputStream inputStream) 
						throws IOException {
					// I wonder why the encoding of inputstream is actually gbk, 
					// while the qq document says the json result should be utf-8. SB 腾讯 ?
					return RequestUtils.saveStreamAsGBK(inputStream);
				}
			});
	
	private static void connectServer() throws Exception {
		ExmailClientRequest request = (ExmailClientRequest) ExmailClientRequest
				.listeningLocation(OAuth.URI_LISTEN)
				.setAccessToken(ExmailUtils.getLatestAccessToken())
                .setClientVersion(ExmailUtils.getLatestVersion())
                .buildQueryMessage();
		
        ListeningResponse jsonResponse = 
        		(ListeningResponse) client.connectServer(request, ListeningResponse.class);
        if (jsonResponse == null) return;
        if (jsonResponse.isInvalidToken()) {
        	ExmailUtils.refreshAccessToken();
        }
        
        if (!StringUtils.isEmpty(jsonResponse.getRet())) {
//        	logger.info("we have recieve a 'Ret' status value: " + jsonResponse.getRet());
        	return;
        }
        
    	// receive version info
        String version = jsonResponse.getVersion();
    	if (!StringUtils.isEmpty(version)) {
    		// persist version
    		ResourceManager.setValue(JinmeiConsts.MAIL_LATEST_VERSION, version);
    		logger.info("we have recieve a version value: " + version);
    		return;
    	}
    		
    	// receive new mail info
    	NewMailInfo newMail = jsonResponse.getNewMailInfo();
    	if (newMail != null) {
    		System.out.println(new String(newMail.getSubject().getBytes(),"UTF-8"));
    		logger.info("we have recieve a new mail. its reciever is: " + newMail.getReceiver() +
    				" and its subject is " + newMail.getSubject());
    		new NewMailMessageSender().sendNewmailMessage(newMail);
    	}
	}
	
	
	/**
	 *  Long connection to exmail server
	 *  
	 * @param args
	 * @throws Exception
	 */
	public static void longConnect() {
        new Thread() {
            @Override
            public void run() {
                int errorCount = 0;
                while (true) {
                    if (errorCount >= 10) {
                        try {
                        	// when failed for above 10 times, we rest for a internal time.
                            Thread.sleep(15000);
                        } catch (InterruptedException e) {
                            break;
                        }
                    }
                    try {
                    	connectServer();
                        errorCount = 0;
                    } catch (MalformedURLException e) {
                        errorCount++;
                    } catch (IOException e) {
                        errorCount++;
                    } catch (Exception e) {
                        errorCount++;
                    } 
                }
            }
        }.start();
    }
	
	/**
	 * Test Method
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		longConnect();
	}
	
}
